package com.crm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crm.entity.UserRoles;
import com.crm.entity.Users;
import com.crm.service.UserRolesService;
import com.crm.util.Result;

//用户和角色的控制层
@RestController
@RequestMapping("/UserRoles")
public class UserRolesController {
	@Autowired
	private UserRolesService userRolesService;

	/**
	 * 根据用户id去添加角色
	 * 
	 * @return
	 */
	@RequestMapping("/addUsersByIdRoles")
	public Object addUsersByIdRoles(UserRoles userRoles, @RequestParam("ids") Object ids, int userId) {
		JSONArray js = JSON.parseArray(ids.toString());// 将从ids.toString()中获得的字符串直接转换成对象
		Integer jg = 0;
		for (Object i : js) {//循环着去添加
			userRoles.setUserId(userId);
			userRoles.setRoleId(Integer.parseInt(i.toString()));
			jg += userRolesService.addUsersByIdRoles(userRoles);
		}
		if (jg == js.size()) {
			return new Result("0", "添加成功", jg, "后台请求成功");
		}
		Result result = new Result("0", "true", 100, "后台请求成功");
		return result;
//		System.out.println(userRoles);
//		Result result=new Result("0", "true", userRolesService.addUsersByIdRoles(userRoles), "后台请求成功");
//		return result;
	}

	/**
	 * 根据用户id和角色id去删除角色
	 * 
	 * @return
	 */
	@RequestMapping("/removeUsersByIdRoles")
	public Object removeUsersByIdRoles(UserRoles userRoles, @RequestParam("ids") Object ids, int userId) {
		JSONArray js = JSON.parseArray(ids.toString());// 将从ids.toString()中获得的字符串直接转换成对象
		Integer jg = 0;
		for (Object i : js) {//循环着去添加
			userRoles.setUserId(userId);
			userRoles.setRoleId(Integer.parseInt(i.toString()));
			jg += userRolesService.removeUsersByIdRoles(userRoles);
		}
		if (jg == js.size()) {
			return new Result("0", "移除成功", jg, "后台请求成功");
		}
		Result result = new Result("0", "true", 100, "后台请求成功");
		return result;
//		System.out.println(userRoles);
//		Result result=new Result("0", "true", userRolesService.removeUsersByIdRoles(userRoles), "后台请求成功");
//		return result;
	}
}
